package com.fy.utilsproject.utils.math;

import com.fy.utilsproject.utils.math.entity.TwoDimensionalCoordinate;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 二次函数：y = ax² + bx + c
 * 顶点坐标：(-b/2a,(4ac-b²)/4a)
 */
public class QuadraticFunction {

    private double a;
    private double b;


    private double c;
    private List<TwoDimensionalCoordinate> coordinateList = new ArrayList<>();

    public double getA() {
        return a;
    }

    public void setA(double a) {
        this.a = a;
    }

    public double getB() {
        return b;
    }

    public void setB(double b) {
        this.b = b;
    }

    public double getC() {
        return c;
    }

    public void setC(double c) {
        this.c = c;
    }

    /**
     * 添加坐标点
     *
     * @param x X轴坐标
     * @param y Y轴坐标
     */
    public void addCoordinate(double x, double y) {
        coordinateList.add(new TwoDimensionalCoordinate(x, y));
    }

    /**
     * 添加坐标点
     *
     * @param coordinate 二维坐标
     */
    public void addCoordinate(TwoDimensionalCoordinate coordinate) {
        coordinateList.add(coordinate);
    }

    public boolean calculation() {
        if (coordinateList.size() == 3) {
            //FIXME 这里只是假设得到的三个点刚好都是函数上的点时计算的结果，如果三个点没有都在函数上则计算结果应该是false，但这里暂未涉及
            //如果集合中已经保存了3个坐标点则取这3个坐标点进行计算
            //https://blog.csdn.net/qq_43391414/article/details/105669099
            TwoDimensionalCoordinate coordinate1 = coordinateList.get(0);
            TwoDimensionalCoordinate coordinate2 = coordinateList.get(1);
            TwoDimensionalCoordinate coordinate3 = coordinateList.get(2);
            double temp1 = (coordinate2.y - coordinate1.y) / (coordinate2.x - coordinate1.x);
            double temp2 = (coordinate3.y - coordinate1.y) / (coordinate3.x - coordinate1.x);
            a = (temp1 - temp2) / (coordinate2.x - coordinate3.x);
            b = temp1 - a * (coordinate1.x + coordinate2.x);
            c = coordinate1.y - b * coordinate1.x - a * coordinate1.x * coordinate1.x;
            return true;
        } else if (coordinateList.size() > 2) {
            //如果集合中的坐标点数量大于2则计算近似解
        }
        return false;
    }

    public double getY(double x) {
        return x * x * a + b * x + c;
    }

    public double getX(double y) {
        //只求正解
        return Float.parseFloat(new DecimalFormat("0.000000000").format((Math.sqrt(b * b - 4 * a * (c - y)) - b) / (2 * a)));
    }

}
